#!/bin/bash
root=$(cd $(dirname $0) && pwd)
export JKZUC_ROOT=/usr/etc/jkzuc
export LD_LIBRARY_PATH=$JKZUC_ROOT/bin:$LD_LIBRARY_PATH
export PYTHONPATH=$JKZUC_ROOT/python3

echo "workspace $JKZUC_ROOT"
DEF_CFG_DIR=$JKZUC_ROOT/configs/default/
CFG_DIR=$JKZUC_ROOT/configs/JAKA/
BIN_DIR=$JKZUC_ROOT/bin
PYTHON=$JKZUC_ROOT/python3/.venv/bin/python
trap 'cleanup ; exit 0' SIGINT SIGTERM

CABTYPE=2
SIM_OPT=

cleanup(){
    $BIN_DIR/jkzuc-clean
}

check_upgrade(){
    # FIXME:后续优化逻辑
    $PYTHON $BIN_DIR/jaka_upgrade_loader.pyc
}

check_parm(){
    for arg in "$@"; do
        case $arg in
            -s)
            SIM_OPT="-S"
            ;;
            -c*)
            CABTYPE="${arg:2}"  # 获取-c后面的参数
            ;;
        esac
    done
}

start_redis() {
    echo "start redis server"
    $BIN_DIR/redis-server $DEF_CFG_DIR/redis.conf
}

check_jkzuc(){
    LOCKFILE=/tmp/jkzuc.lock
    if [ -f $LOCKFILE ]; then
        echo -n "JkZuc is still running.  Restart it? [Y/n] "
        read input
        [ -z $input ] && input=y

        case $input in
        y | Y | yes)
            echo Cleaning up old JkZuc...
            cleanup
            ;;
        *)
            echo Not starting new JkZuc
            exit 0
            ;;
        esac
    fi
    touch $LOCKFILE
}

start_addon(){
    if [ `$(which uname) -m` == x86_64 ];then
        python $BIN_DIR/start_addon_manager &
    fi
}

check_cabinet(){
    $BIN_DIR/cabidentify
    CABTYPE=$?
    # 返回的-1在shell中就是255,此时为了启动成功设置柜子类型为cab2.1
    if [ $CABTYPE = 255 ];then
        CABTYPE=2
    fi
}

# 预备阶段
check_jkzuc
check_upgrade
check_cabinet
check_parm $@
echo "CAB=$CABTYPE SIM=$SIM_OPT"

# 启动
$BIN_DIR/zuctaskmod -c 6 -S &
sleep 2

# fixme
# /usr/bin/profinet ens33 &
# /usr/bin/ethernetip ens36 &
# start_addon
$PYTHON $PYTHONPATH/jaka_server.pyc
result=$?

# 结束清理阶段
cleanup
exit $result